<?php

namespace app\common\library;

use think\Cache;

class FireFace
{
    protected static $key = "fire_face_config";
    protected static $list = [];
    protected static $position = 0; // 迭代

    // 设置火脸账号列表
    public function __construct()
    {
        // 获取缓存
        if (Cache::store('redis')->has(self::$key)){
            self::$list = Cache::store('redis')->get(self::$key);
        }else{
            self::update();
        }
    }

    // 随机获取账号
    public function random()
    {
        if (empty(self::$list)){
            return false;
        }

        return self::$list[array_rand(self::$list)];
    }

    // 获取固定账号
    public function getRow($id)
    {
        if (empty(self::$list)){
            return false;
        }

        if (!isset(self::$list[$id])){
            return false;
        }

        return self::$list[$id];
    }
    
    // 迭代轮询
    public function iteration()
    {
        $list = ksort(self::$list);
        $list = array_values($list);
        if (empty($list)){
            return false;
        }
        if (Cache::store('redis')->has("fire_face_position")){
            self::$position = Cache::store('redis')->get("fire_face_position");
            if (self::$position >= count($list)){
                $position = 0;
            }else{
                $position = self::$position + 1;
            }
            Cache::store('redis')->set("fire_face_position",$position);
        }else{
            self::$position = Cache::store('redis')->set("fire_face_position",self::$position++);
        }

        return $list[self::$position];
    }

    // 更新缓存
    public static function update()
    {
        $list = db('fire_face_config')->where(['status'=>'normal'])->column('*','id');
        self::$list = $list;
        Cache::store('redis')->set(self::$key,$list);
        return $list;
    }
}